<?php

class Store_Module extends Module{

	function __construct(){
		$this->cityid = Base::getCityId();
		$this->user = new AdminUser();
	}

	function filteStore($post, $edit = false) {
		$payments = array(
			1 => '餐到付款',
			2 => '在线付款',
			3 => '餐到或在线付款',
		);

		$data = array(
			'status'		=> array_get_bool($post, 'status', 1, 0),						//状态
			'zone_id'		=> array_get_int($post, 'zone_id'),								//区域
			'subzone_id'	=> array_get_int($post, 'subzone_id'),							//板块
			'name'			=> array_get_string($post, 'name'),								//餐厅名字
			'ename'			=> array_get_string($post, 'ename'),							//英文名字
			'nickname'		=> array_get_string($post, 'nickname'),							//餐厅别名
			'letter'		=> array_get_match($post, 'letter', '/^[a-zA-Z]$/i', ''),		//字母
			'ordnum'		=> array_get_int($post, 'ordnum'),								//排序
			'call_number'	=> array_get_string($post, 'call_number'),						//订餐号码
			'min_charge'	=> array_get_int($post, 'min_charge'),							//最低消费
			'min_order'		=> array_get_range($post, 'min_order', array(1, 10), 1),		//起送份数
			'payment'		=> array_get_enum($post, 'payment', array_keys($payments), 1),	//付款方式
			'extra_pay'		=> array_get_string($post, 'extra_pay'),						//送餐费规则,
			'telphone'		=> array_get_string($post, 'telphone'),							//电话号码1
			'telphone2'		=> array_get_string($post, 'telphone2'),						//电话号码2
			'telphone3'		=> array_get_string($post, 'telphone3'),						//电话号码2
			'address'		=> array_get_string($post, 'address'),							//地址
			'picture'		=> array_get_string($post, 'picture'),							//图片
			'service_time'	=> join('-', array_get($post, 'service_time')),					//营业时间
			'delivery_time'	=> $this->praseDeliveryTime($post),								//送餐时间
			'delivery_area'	=> array_get_string($post, 'delivery_area'),					//送餐范围
			'city_deliver'	=> array_get_bool($post, 'city_deliver', 1, 0),					//是否全市配送
			'longitude'		=> array_get_double($post, 'longitude'),						//经度
			'latitude'		=> array_get_double($post, 'latitude'),							//维度
			'memo'			=> array_get_string($post, 'memo'),								//备注信息
		);

		if($edit){
			$data['update_uid']	= $this->user->getId();
			$data['update_dt']	= $this->currentTime();
		}else{
			$data['city_id']	= $this->cityid;
			$data['update_uid']	= $this->user->getId();
			$data['update_dt']	= $this->currentTime();
			$data['create_uid']	= $this->user->getId();
			$data['create_dt']	= $this->currentTime();
		}

		return $data;
	}

	function getStore($id){
		return DB::getOne(DB::getSql('*', 't_store', 'res_id = '.intval($id)));
	}

	function getDeliver($id){
		return DB::getAll(DB::getSql('*', 't_deliver', 'res_id = '.intval($id)), null, 'zone_id');
	}

	function listStore($search = array(), $limit=20){
		$equal = $like = array();
		$where = '1 = 1';
		if(is_array($search)){
			if(isset($search['cat_id']) && $search['cat_id']){
				$equal['cat_id']  = intval($search['cat_id']);
			}

			if(isset($search['zone_id']) && $search['zone_id']){
				$equal['zone_id'] = intval($search['zone_id']);
			}

			if(isset($search['subzone_id']) && $search['subzone_id']){
				$equal['subzone_id'] = intval($search['subzone_id']);
			}

			if(isset($search['name']) && $search['name']){
				$like['name'] = $search['name'];
			}

			foreach($equal as $k => $v){
				$where .= " AND `{$k}` = ".DB::quote($v);
			}
			if($like['name']){
				$name = DB::escape($like['name']);
				if(is_numeric($name)){
					$where .= " AND (`res_id` = $name OR `telphone` Like '%{$name}%' OR `telphone3` Like '%{$name}%' OR `telphone2` Like '%{$name}%')";
				}else{
					$where .= " AND (`name` Like '%{$name}%')";
				}
			}
			$query = $equal + $like;
		}

		$limit  = intval($limit);
		$sql    = DB::getSql('count(*)', 't_store', $where);
		$total  = DB::getFirst($sql);

		if($total){
			Base::loadLibrary('Pager');
			$pager  = new Pager($total, $limit);
			$offset = $pager->getOffset();

			$sql    = DB::getSql('*', 't_store', $where, "{$offset}, {$limit}", 'ordnum DESC, res_id ASC');
			$data   = DB::getAll($sql);

			$urltpl = Base::adminUrl('store', 'index', $query).'&page={PAGE}';
			$pagestring = $pager->adminPageLink($urltpl);
		}else{
			$data   = array();
			$pagestring = '';
		}
		return array($total, $data, $pagestring);
	}

	function changeDeliver($id, $post){
		$res_id = intval($id);

		DB::prepare('delete from `t_deliver` where res_id = ?')->execute(array($res_id));
		if(!$post['city_deliver']){
			$deliver_zone = array_get($post, 'deliver_zone');
			$zone_all = array_get($post, 'zone_all');
			$parent_zone  = $array = array();
			if($zone_all || $deliver_zone){
				$zone = Base::loadModule('zone', true);
				$zone->initCity();

				//判断区域
				if(is_array($zone_all)){
					foreach($zone_all as $zid){
						$parent_zone[$zid] = 1;
					}
				}

				//判断二级版块
				if(is_array($deliver_zone)){
					foreach($deliver_zone as $dzone){
						$pid = $zone->getZoneById($dzone)->parent_id;
						if(isset($parent_zone[$pid]) && $parent_zone[$pid]){ //如果已经是“全区”，就不必处理
							continue;
						}
						$array[] = array(
							$res_id, $dzone, 0
						);
						$parent_zone[$pid] = 0;
					}
				}

				//处理区域
				foreach($parent_zone as $zone_id => $all_zone){
					$array[] = array(
						$res_id, $zone_id, $all_zone,
					);
				}

				$stmt = DB::prepare("insert into `t_deliver` (res_id, zone_id, all_zone) values (?, ?, ?)");
				foreach($array as $data){
					$stmt->execute($data);
				}
			}
		}else{ //全市可送
			$data = array(
				'res_id'  => $res_id,
				'zone_id' => 0,
				'all_zone'=> 1,
			);
			DB::insert('t_deliver', $data);
		}
	}

	function addStore($post){
		DB::insert('t_store', $this->filteStore($post));
		$res_id = DB::lastInsertId();

		$this->changeDeliver($res_id, $post);
		return true;
	}

	function editStore($id, $post){
		$res_id = intval($id);
		DB::update('t_store', $this->filteStore($post, true), "res_id = {$res_id}");

		$this->changeDeliver($res_id, $post);
		return true;
	}

	function delStore($id){
		return DB::prepare("delete `t_store` where `res_id` = ?")->execute(array($res_id));
	}

	function delStoreArray($ids){
		$stmt = DB::prepare("delete `t_store` where `res_id` = ?");
		foreach($ids as $res_id){
			$stmt->execute(array($res_id));
		}
		return true;
	}

	function sortStoreArray($sorts){
		$stmt = DB::prepare("update `t_store` set `ordnum` = ? where `res_id` = ?");
		foreach($sorts as $res_id => $ordnum){
			$stmt->execute(array($ordnum, $res_id));
		}
		return true;
	}

	function statStoreArray($ids, $status){
		$status = $status ? 1 : 0;
		$res_id = intval($res_id);

		$stmt = DB::prepare("update `t_store` set `status` = ? where `res_id` = ?");
		foreach($ids as $res_id){
			$stmt->execute(array($status, $res_id));
		}
		return true;
	}

	private function praseDeliveryTime($post){
		$times = array_get($post, 'delivery_time');

		if(($times[2] && $times[3])){
			if($times[2] <= $times[1]){
				$time = $times[0].'-'.$times[3];
			}else{
				$time = $times[0].'-'.$times[1].' '.$times[2].'-'.$times[3];
			}
		}else{
			$time = $times[0].'-'.$times[1];
		}
		return $time;
	}
}
?>